package com.scalar.chiptrack.operations.dataentry.rmaReceive.actioncommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.operations.dataentry.rmaReceive.forms.RMAReceiveForm;
import com.scalar.chiptrack.operations.dataentry.dao.DataEntryDAO;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.process.dao.FabStage;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.notification.dao.NotificationDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.Mailer;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * User: ChandraSekhar
 * Date: Aug 29, 2008
 * Time: 5:22:54 PM
 */
public class RMAReceiveSaveCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/rmaReceive.do";

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception
    {

        RMAReceiveForm rmaReceiveForm = (RMAReceiveForm) form;

        HashMap errors = new HashMap();
        HashMap info = new HashMap();
        String action = request.getParameter("action");

        request.setAttribute(INFO_MESSAGES, info);
        request.setAttribute(ERROR_MESSAGES, errors);

        HttpSession mSession = request.getSession();
        User user = (User) mSession.getAttribute(SessionKeys.USER_KEY);
        DBTransaction dbTranasaction    = null;
        if (user == null)
        {
            mSession.setAttribute(SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME);
            return (mapping.findForward("login"));
        }
        else
        {
            if (user.isActionAllowed(Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY))
            {
                request.setAttribute("showMessage", "FALSE");
            }
            else
            {
                request.setAttribute("showMessage", "TRUE");
            }
        }

        try
        {               
            DataEntryDAO.saveRMAReceiveInfo( dbTranasaction, rmaReceiveForm, user.getUserName() );

            notifyUserAboutRMAReceiveLots( rmaReceiveForm , Constants.RMA_RECEIVE_NOTIFICATION );

            resetToken( request );
            info.put("RMA Lots received Successlly", null);
            info.put("Notification mail sent Successlly", null);
            request.setAttribute("customersList", CustomerDAO.getAllCustomerNamesNoStringsAttached() );
            request.setAttribute("action", action);
       }
       catch( Exception e)
       {
          request.setAttribute("customersList", CustomerDAO.getAllCustomerNamesNoStringsAttached() );
          errors.put( "Could not save RMA Lot details", null);
          e.printStackTrace();
       }
       finally{
            rmaReceiveForm.setCustomerId(-1);
            rmaReceiveForm.setRmaReceiveId(0);
            rmaReceiveForm.setRmaReceiveNo("");
            rmaReceiveForm.setRmaReceiveLotsList( null);
        }
        return mapping.findForward("rmaReceive");
    }

    public static boolean notifyUserAboutRMAReceiveLots( RMAReceiveForm rmaReceiveForm, String nsType ) throws Exception
    {
        ArrayList rmaReceiveLotsList = rmaReceiveForm.getRmaReceiveLotsList();
        if ( rmaReceiveLotsList == null || rmaReceiveLotsList.size() <= 0 )
        {
            return false;
        }

        boolean success     = false;
        String[] emailArray = null;
        LotDetails rmaReceiveLots = null;
        emailArray = NotificationDAO.loadEmailsByNSType( null, null, nsType );


        String from = ConfigManager.getScalarAdminEmail();
        int index = from.lastIndexOf("\\");
        from  = from.substring( index+1, from.length() );
        String to = null;
        if ( emailArray != null && emailArray.length > 0 )
        {
            to   = StringUtils.concatStrings ( emailArray, Mailer.EMAIL_SEPARATOR );
        }
        else
        {
            System.out.println("RMA Receive Lots Notification not set up for users");
            return success;
        }
        String subject = "RMA Received Lots from Customer";

        // FORMAT MESSAGE
        StringBuffer buf = new StringBuffer( 2098 );
        buf.append( "<HTML><HEAD><META http-equiv=Content-Type content='text/html; charset=BIG5'></HEAD><BODY>" );
        buf.append( "<TABLE ALIGN = 'CENTER' style='FONT-SIZE: 8pt; COLOR: black; FONT-FAMILY: Verdana' borderColor='#ffffff' cellSpacing='1' cellPadding='3' width='50%' border=0>" );
        buf.append( "<TR bgColor='#ccccff'><TD colspan='6' width='100%' align='center'><B>RMA RECEIVED LOTS FROM CUSTOMER <B></TD>" );
        buf.append( "<TR bgColor='#e6e6e6'><TD width='2%' align='CENTER'><B>SL NO.<B></TD><TD width='20%' align='CENTER'><B>CUSTOMER<B></TD>");
        buf.append( "<TD width='10%' align='CENTER'><B>RMA NO<B></TD><TD width='20%' align='CENTER'><B>CUSTOMER PART<B></TD>");
        buf.append( "<TD width='8%' align='CENTER'><B>LOT NUMBER<B></TD><TD width='8%' align='CENTER'><B>LOT QTY<B></TD></TR>");
        /*buf.append( "<TD width='8%' align='CENTER'><B>VENDOR<B></TD>" );*/
         int sno = 1;
        for ( int i = 0; i < rmaReceiveLotsList.size(); i++ )
        {
            rmaReceiveLots = (LotDetails) rmaReceiveLotsList.get(i);

            if ( rmaReceiveLots.isChecked() && !(rmaReceiveLots.getRmaReceiveLotId() > 0 ) )
            {                   
                buf.append("<TR bgColor='#e6e6e6'><TD width='2%' align='CENTER'>").append(sno).append(".").append("</TD>");
                buf.append("<TD width='35%'align='CENTER'>").append(CustomerDAO.getCustomerDetails(rmaReceiveForm.getCustomerId() ).getCustomerName()).append("</TD>");
                buf.append("<TD width='12%' align='CENTER'>").append(rmaReceiveForm.getRmaReceiveId() > 0 ? DataEntryDAO.getRmaNumber( rmaReceiveForm.getRmaReceiveId() ) : rmaReceiveForm.getRmaReceiveNo()  ).append("</TD>");
                buf.append("<TD width='35%' align='CENTER'>").append( ProductDao.getDeviceName( Integer.parseInt(rmaReceiveLots.getProcessStepId() ) ) ).append("</TD>");
                buf.append("<TD width='8%' align='CENTER'>").append(rmaReceiveLots.getLotNumber()).append("</TD>");
                buf.append("<TD width='8%' align='CENTER'>").append(rmaReceiveLots.getDieQtyIn()== null ? "":rmaReceiveLots.getDieQtyIn()).append("</TD></TR>");
                /*buf.append("<TD width='8%' align='CENTER'>").append(rmaReceiveLots.getLocationId() ).append("</TD>");*/
                sno++;
            }
        }
        buf.append( "</TR></TABLE></BODY></HTML>\n" );
        String message = buf.toString();

        try
        {
            // SEND MESSAGE
            Mailer.send ( from, to, null, null, subject, message, null, Mailer.CONTENT_TYPE_HTML, false );
            success = true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            success = false;
            System.out.println("Exception while sending new Lot mail notification");
        }

        return success;
    }
}
